package com.example.SBootDemo.Filter;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.example.SBootDemo.Dao.Interface.funDao;
import com.example.SBootDemo.model.function.function;
import com.example.SBootDemo.model.function.role;
import com.example.SBootDemo.model.function.user;
import com.example.SBootDemo.service.Interface.function.funinterface;
import com.example.SBootDemo.service.Interface.function.userinterface;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private userinterface userInfoService;
   
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        user userInfo  = (user)principals.getPrimaryPrincipal();
        
        role role=userInfo.getRole();
            authorizationInfo.addRole(role.getRolename());
            
            for(function p:role.getFunlist()){
            	System.out.println(p.getUrl());
                authorizationInfo.addStringPermission(p.getUrl());
            }
            
        
        return authorizationInfo;
    }

 
    
    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        System.out.println(token.getCredentials());
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        user user = userInfoService.findByUsername(username);
        //user的role的funlist是在使用user.getRole().getFunlist()时
        //jpa才会调用方法 查询（减轻负担）所以会出现其他地方通过user得不到funlist显示no session.
       

        
        if(user == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
        		user, //用户名
                user.getPassword(), //密码
                
                getName()  //realm name
        );
        return authenticationInfo;
    }

}